package com.pqc.tbk.web.order;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.pqc.tbk.entity.order.Order;
import com.pqc.tbk.service.order.OrderService;
import com.pqc.tbk.utils.Pager;
import com.pqc.tbk.utils.UserUtil;

/**
 * 
 * @author long, create on 2012-7-19 下午2:04:38
 * 
 */
@Controller
@RequestMapping(value = "/user/home/")
public class OrderController {

	private OrderService orderService;

	@RequestMapping(value = "order_history")
	public String toOrderHistory() {
		return "money/order_history";
	}

	/**
	 * 订单列表进行分页的结果
	 * 
	 * @param cpage
	 * @param map
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "orderList/{cpage}")
	public String getOrders(@PathVariable("cpage") final long cpage,
			final ModelMap map) {
		// long uid = Long.parseLong(CookiesCRUD.getCookieByName(request,
		// "user_id"));
		final long uid = UserUtil.getUID();
		Pager<Order> pager = initPager(cpage, uid);
		pager = orderService.getOrders(pager, uid);
		map.put("pager", pager);
		return "money/order_history_table";
	}

	// pager对象的初始化
	public Pager<Order> initPager(long cpage, final long uid) {
		final Pager<Order> pager = new Pager<Order>();
		// 到时候pagesize从Application中获取
		pager.setPageSize(10L);
		pager.setTotal(orderService.getCountByUid(uid));
		final long pages = (pager.getTotal() % pager.getPageSize()) == 0 ? pager
				.getTotal() / pager.getPageSize()
				: (pager.getTotal() / pager.getPageSize()) + 1;
		pager.setPages(pages);
		if (cpage > pager.getPages()) {
			cpage = pager.getPages();
		}
		if (cpage < 1) {
			cpage = 1L;
		}
		pager.setNum(cpage);
		pager.setOffSet((cpage - 1) * pager.getPageSize());
		return pager;
	}

	@Autowired
	public void setOrderService(final OrderService orderService) {
		this.orderService = orderService;
	}

}
